package com.fionera.sample.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fionera.sample.R;
import com.fionera.sample.application.Demo;
import com.fionera.sample.bean.LoginBean;
import com.fionera.sample.constant.SPConstants;
import com.fionera.sample.constant.UrlConstants;
import com.fionera.base.util.MD5Util;
import com.fionera.sample.util.OkHttpUtil;
import com.fionera.sample.util.SPUtil;
import com.fionera.sample.util.ShowToast;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wsdk.service.BluetoothLeService;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;

public class LoginActivity
        extends BaseActivity
        implements View.OnClickListener {

    private TextView mTvTitle;
    private EditText mEtUsername;
    private EditText mEtPsw;
    private TextView btnLogin;
    private String userName;
    private String psw;
    private LoginBean loginBean;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        String ip = Demo.getInstance().getIp();
        Demo.getInstance().changeIp(ip);

        initView();

        setListener();

        new RxPermissions(this).request(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CALL_PHONE, Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION).subscribe(
                new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) {
                        if (granted) {
                            initData();
                        } else {
                            ShowToast.shortTime("请授予必要的权限");
                            finish();
                        }
                    }
                });
    }

    private void initView() {
        mTvTitle = findViewById(R.id.login_tv_title);
        mEtUsername = findViewById(R.id.login_et_username);
        mEtPsw = findViewById(R.id.login_et_psw);
        btnLogin = findViewById(R.id.btn_login);
        mEtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mEtPsw.setText("");
            }
        });
    }

    private void setListener() {
        btnLogin.setOnClickListener(this);
    }

    private void initData() {
        if (SPUtil.getBoolean(SPConstants.REMEMBERUSER)) {
            mEtUsername.setText(SPUtil.getString(SPConstants.USER_NAME));
            mEtPsw.setText(SPUtil.getString(SPConstants.USER_PSW));
        }
        checkIP(Demo.getInstance().getIp());
    }

    /**
     * 检查Ip地址是否可用
     * @param ip ip地址
     */
    private void checkIP(final String ip) {
        getMProcessDialog().setTitle("正在设置服务器地址").showNormal();
        getEnqueueWithoutToken(UrlConstants.BASE_DATA, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                getMProcessDialog().dismiss();
                Demo.getInstance().changeIp(ip);

                JSONObject rawObject = null;
                try {
                    rawObject = new JSONObject(json);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mTvTitle.setText("测试系统");
            }

            @Override
            public void onFailed(String reason) {
                getMProcessDialog().dismiss();
                ShowToast.shortTime(reason);
            }
        });
    }

    private void login() {
        userName = mEtUsername.getText().toString().trim();
        psw = mEtPsw.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(psw)) {
            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        getMProcessDialog().setTitle("正在登录").showNormal();
        Map<String, String> params = new HashMap<>();
        params.put("username", userName);
        params.put("password", MD5Util.md5(psw));
        postJsonEnqueue(UrlConstants.LOGIN, params, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                getMProcessDialog().dismiss();
                SPUtil.setBoolean(SPConstants.REMEMBERUSER, true);
                SPUtil.setString(SPConstants.USER_NAME, userName);
                SPUtil.setString(SPConstants.USER_PSW, psw);
                SPUtil.setString(SPConstants.LOGIN_JSON, json);
                loginBean = new Gson().fromJson(json, LoginBean.class);
                SPUtil.setString(SPConstants.EQUIPSN, loginBean.getEquipRegisterInfo().getSn());
                SPUtil.setString(SPConstants.CORE_SN, TextUtils
                        .isEmpty(loginBean.getEquipRegisterInfo().getEmbededSn()) ? loginBean
                        .getEquipRegisterInfo().getSn() : loginBean.getEquipRegisterInfo()
                        .getEmbededSn());
                SPUtil.setString(SPConstants.TOKEN, loginBean.getToken());
                SPUtil.setString(SPConstants.USER_ID, loginBean.getUserLogin().getId());
                SPUtil.setString(SPConstants.USER_TYPE, loginBean.getUserLogin().getUserType());
                SPUtil.setString(SPConstants.AVATAR, loginBean.getUserLogin().getAvatar());
                SPUtil.setString(SPConstants.REAL_NAME, loginBean.getUserLogin().getRealName());
                SPUtil.setString(SPConstants.DEPARTMENT, loginBean.getUserLogin().getDepartment());
                SPUtil.setString(SPConstants.USER_NAME, loginBean.getUserLogin().getUsername());
                SPUtil.setString(SPConstants.PHONE, loginBean.getUserLogin().getPhone());
                SPUtil.setString(SPConstants.ROLENAME, loginBean.getUserLogin().getRoleName());
                SPUtil.setString(SPConstants.RECEIVE_MESSAGE, loginBean.getUserLogin().getReceiveMsg());
                SPUtil.putStrListValue(mContext, SPConstants.AUTHORITY,
                        loginBean.getUserLogin().getAuthority());

                toForward();
            }

            @Override
            public void onFailed(String reason) {
                getMProcessDialog().dismiss();
                ShowToast.shortTime(reason);
            }
        });
    }

    private void toForward() {
        switch (loginBean.getUserLogin().getUserType()) {
            case "EQUIP_ADMIN":
            case "EQUIP_OPERATOR":
                Intent intent = new Intent(mContext, StampListActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        /*
          login stop service
         */
        stopService(new Intent(mContext, BluetoothLeService.class));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                login();
                break;
            default:
                break;
        }
    }
}
